package cn.mdmbct.spring.starter.douyin.basis.config;

import cn.mdmbct.douyin.basis.service.DyBasisServiceImpl;
import cn.mdmbct.douyin.basis.service.interfaces.DyBasisService;
import cn.mdmbct.douyin.common.config.HttpConfig;
import cn.mdmbct.douyin.common.http.apache.ApacheHttpExecutorFactory;
import cn.mdmbct.douyin.common.http.okhttp.OkHttpExecutorFactory;
import cn.mdmbct.douyin.common.storage.DyStorageManager;
import cn.mdmbct.spring.starter.douyin.common.properties.dy.DyOpenApiProperties;
import cn.mdmbct.spring.starter.douyin.common.properties.dy.HttpProperties;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 基本open api自动配置
 *
 * @author mdmbct  mdmbct@outlook.com
 * @date 2021/3/9 13:39
 * @modified mdmbct
 * @since 1.0
 */
@Configuration
public class DyOpenApiBasisServiceAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean
    public DyBasisService dyBasisService(DyOpenApiProperties apiProperties, DyStorageManager storageManager) {

        HttpProperties httpProperties = apiProperties.getHttp();
        HttpConfig httpConfig = new HttpConfig();
        BeanUtils.copyProperties(httpProperties, httpConfig);
        switch (httpProperties.getType()) {
            case OK_HTTP:
                return getDyBasisServiceWithOkHttp(httpConfig, storageManager);
            case APACHE_HTTP:
                return getDyBasisServiceWithApacheHttp(httpConfig, storageManager);
            default:
                return getDefaultDyBasisServiceImpl(httpConfig, storageManager);
        }
    }


    private DyBasisService getDyBasisServiceWithOkHttp(HttpConfig httpConfig, DyStorageManager storageManager) {

        return new DyBasisServiceImpl(storageManager, new OkHttpExecutorFactory().createHttpExecutor(httpConfig));
    }

    private DyBasisService getDyBasisServiceWithApacheHttp(HttpConfig httpConfig, DyStorageManager storageManager) {
        return new DyBasisServiceImpl(storageManager, new ApacheHttpExecutorFactory().createHttpExecutor(httpConfig));
    }

    private DyBasisService getDefaultDyBasisServiceImpl(HttpConfig httpConfig, DyStorageManager storageManager) {
        return getDyBasisServiceWithOkHttp(httpConfig, storageManager);
    }

}
